/**
 * Created by S on 2016/3/21.
 */
var DBTool=require('commom').DBTool;

exports.insertuser=function(condition,callback){
    var sql="insert into administrator(username,password) values('" + escape(condition.username) +"','"+escape(condition.password) +"')";
    var params=[];
    DBTool.Execute(sql,params,function(err,data){
        if(err)
        {
            callback(err,null);
        }
        else
        {
            callback(null,data);
        }
    });
}

exports.finduser = function (condition,callback) {
    var star=false;
    var c="where";
    var sql="select * from administrator ";
    if(condition.id!=undefined){
        if(star)
            c=c+" and ";
        c=c+" id = "+condition.id;
        star=true;
    }
    if(condition.username!=undefined){
        if(star)
            c=c+" and ";
        c=c+" username = '"+escape(condition.username)+"'";
        star=true;
    }
    if(condition.password!=undefined){
        if(star)
            c=c+" and ";
        c=c+" password = '"+escape(condition.password)+"'";
        star=true;
    }
    if(c!="where"){
        sql=sql + c;
    }
    var params=[];
    DBTool.Execute(sql,params, function ( err, data ) {
        if(err)
        {
            callback(err,null);
        }
        else
        {

            if(data.length>0)
            {
                var i=0;
                changedata(i)
                function changedata(c)
                {
                    data[c].username=unescape(data[c].username);
                    data[c].password=unescape(data[c].password);
                    i++;
                    if(i<data.length)
                    {
                        changedata(i);
                    }
                    else
                    {
                        callback(null,data);
                    }
                }
            }
            else
            {
                callback(null,data);
            }
        }
    });
};

exports.changeuser=function(condition,callback){
    var sql="update administrator set password = '"+escape(condition.password) +"' where id = "+condition.id;
    var params=[];
    DBTool.Execute(sql,params,function(err,data){
        if(err)
        {
            callback(err,null);
        }
        else
        {
            callback(null,data);
        }
    });
}

exports.deleteuser=function(condition,callback){
    var sql="delete administrator";
    if(condition.id!=undefined){
        sql=sql+" where id = "+condition.id;
    }
    var params=[];
    DBTool.Execute(sql,params,function(err,data){
        if(err)
        {
            callback(err,null);
        }
        else
        {
            callback(null,data);
        }
    });
}